<template>
  <view class="form-item" :class="{ flex: labelPosition === 'left' }">
    <view class="label" :style="{ width: labelWidth || parentLabelWidth }">
      <text>{{ label }}</text>
      <text v-if="rule.required || required" class="start color-danger">*</text>
    </view>
    <view class="content">
      <slot></slot>
    </view>
  </view>
</template>

<script>
export default {
  name: 'thFormItem',
  components: {},
  data() {
    return {
      parentLabelWidth: '', //父级thForm设置的label宽度
      rule: {},
    };
  },
  props: {
    label: {
      //label的文本
      type: String,
      default: '',
    },
    prop: {
      //表单字段
      type: String,
      default: '',
    },
    labelWidth: {
      //label的宽度
      type: String,
      default: '',
    },
    labelPosition: {
      type: String,
      default: 'left', //label位置 支持left和top
    },
    required: {
      type: Boolean,
      default: false,
    },
  },
  created() {
    const thForm = this.getForm(this.$parent);
    if (thForm?.labelWidth) {
      this.parentLabelWidth = thForm.labelWidth;
    }
    if (thForm?.rules && this.prop) {
      if (thForm.rules[this.prop] && thForm.rules[this.prop]) {
        this.rule = thForm.rules[this.prop];
      }
    }
  },
  methods: {
    // 获取父级中的ThForm组件
    getForm(parent) {
      const parentInfo = this.getParentInfo(parent);
      if (parentInfo.$options?.name === 'thForm') {
        return parentInfo;
      } else if (parentInfo.$parent) {
        return this.getForm(parentInfo.$parent);
      } else {
        return undefined;
      }
    },
    getParentInfo(parent) {
      return parent;
    },
  },
};
</script>

<style scoped lang="scss">
.form-item {
  &.flex {
    display: flex;

    // align-items: flex-start;
    // align-items: start;
    align-items: center;
  }

  position: relative;
  flex: 1;
  min-width: 540rpx;
  padding: 18rpx 0;
  margin: 0 24rpx;

  :deep(.uni-date) {
    .uni-date-x {
      padding: 0;
    }

    .uni-date__x-input {
      height: 40rpx;
      padding: 0;

      .uni-input-placeholder {
        font-size: 0.875rem;
        color: #8a929f;
      }
    }

    .uniui-calendar {
      display: none;
    }
  }

  .my-input {
    flex: 1;

    :deep(.textarea) {
      background-color: #f3f3f3;
    }
  }

  // &:not(:last-child) {
  &::after {
    position: absolute;
    right: 0;
    bottom: 0;
    left: 0;
    height: 1rpx;
    content: '';
    background-color: #f3f3f3;
  }

  // }
  .label {
    flex-shrink: 0;
    width: 120rpx;
    padding: 8rpx 0;
    margin-right: 12rpx;
    font-size: 0.8125rem;
    line-height: 1;
    color: #666;

    // display: flex;
    // align-items: center;
    .start {
      // line-height: 1;
      position: relative;
      top: 6rpx;
      margin-left: 8rpx;
    }
  }

  .content {
    display: flex;
    width: 100%;

    .warning {
      font-size: 0.6875rem;
      color: #f56c6c;
    }
  }

  .placeholder {
    color: #8a929f;
  }
}
</style>
